﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BookSpineCalculatorPro
{
    public partial class MainForm : Form
    {
        // 纸张厚度字典（纸张类型名称 -> 单页厚度mm）
        private Dictionary<string, double> paperThicknessMap;

        // 封面厚度字典（封面类型名称 -> 厚度mm）
        private Dictionary<string, double> coverThicknessMap;

        // 装订方式系数字典（装订方式名称 -> 厚度系数）
        private Dictionary<string, double> bindingFactorMap;

        // 当前单位是否是毫米（false表示英寸）
        private bool isMillimeter = true;

        public MainForm()
        {
            InitializeComponent();
            InitializeDictionaries();
            LoadDefaultValues();
            // 设置初始状态
            groupBoxAdvanced.Visible = false;
            buttonAdvanced.Text = "显示高级选项";

            // 设置初始位置
            buttonCalculate.Top = 340;
            buttonAdvanced.Top = 340;
            buttonSaveConfig.Top = 340;
            groupBoxResults.Top = 170;

            // 初始窗体高度
            this.Height = 480;
        }

        /// <summary>
        /// 初始化各种数据字典
        /// </summary>
        private void InitializeDictionaries()
        {
            // 初始化纸张厚度数据（单位：mm/页）
            paperThicknessMap = new Dictionary<string, double>
            {
                {"双胶纸 60g", 0.075},
                {"双胶纸 70g", 0.085},
                {"双胶纸 80g", 0.095},
                {"双胶纸 100g", 0.11},
                {"双胶纸 120g", 0.12},
                {"铜版纸 80g", 0.075},
                {"铜版纸 105g", 0.09},
                {"铜版纸 128g", 0.11},
                {"铜版纸 157g", 0.13},
                {"道林纸 70g", 0.10},
                {"道林纸 80g", 0.12},
                {"道林纸 90g", 0.13},
                {"道林纸 100g", 0.15}

            };

            // 初始化封面厚度数据（单位：mm）
            coverThicknessMap = new Dictionary<string, double>
            {
                {"无封面", 0.0},
                {"200g铜版纸封面", 0.5},
                {"250g铜版纸封面", 0.6},
                {"300g铜版纸封面", 0.8},
                {"1.5mm灰板纸精装", 3.0},  // 精装书壳厚度
                {"2.0mm灰板纸精装", 4.0},
                {"2.5mm灰板纸精装", 5.0}
            };

            // 初始化装订方式系数
            bindingFactorMap = new Dictionary<string, double>
            {
                {"平装(胶装)", 1.0},
                {"精装(硬壳)", 1.25},
                {"锁线胶装", 1.15},
                {"骑马钉", 0.9},
                {"裸脊装订", 1.3}
            };
        }

        /// <summary>
        /// 加载默认值到界面控件
        /// </summary>
        private void LoadDefaultValues()
        {
            // 加载纸张类型
            var sortedPapers = new List<string>(paperThicknessMap.Keys);
            //sortedPapers.Sort();
            comboPaperType.Items.AddRange(sortedPapers.ToArray());
            comboDefPaper.Items.AddRange(sortedPapers.ToArray());

            // 加载封面类型
            var _comboCoverType = new List<string>(coverThicknessMap.Keys);
            comboCoverType.Items.AddRange(_comboCoverType.ToArray());
            comboDefCover.Items.AddRange(_comboCoverType.ToArray());

            // 加载装订方式
            var _comboBindingType = new List<string>(bindingFactorMap.Keys);
            comboBindingType.Items.AddRange(_comboBindingType.ToArray());

            // 设置默认选中项
            comboPaperType.SelectedIndex = 0;
            comboCoverType.SelectedIndex = 0;
            comboBindingType.SelectedIndex = 0;
            comboDefPaper.SelectedIndex = 0;
            comboDefCover.SelectedIndex = 0;

            // 初始化纸张参考表格
            InitializePaperReferenceGrid();
        }

        /// <summary>
        /// 初始化纸张参考数据表格
        /// </summary>
        private void InitializePaperReferenceGrid()
        {
            dataGridPaperRef.Rows.Clear();

            foreach (var paper in paperThicknessMap)
            {
                string desc = GetPaperDescription(paper.Key);
                dataGridPaperRef.Rows.Add(paper.Key, paper.Value.ToString("F3"), desc);
            }
        }

        /// <summary>
        /// 获取纸张类型的描述信息
        /// </summary>
        private string GetPaperDescription(string paperType)
        {
            if (paperType.Contains("双胶纸")) return "质地柔软，适合书籍";
            if (paperType.Contains("铜版纸")) return "表面光滑，适合彩色印刷";
            if (paperType.Contains("道林纸")) return "耐久性好，适合长期保存的书籍";
            return "通用纸张";
        }

        /// <summary>
        /// 检查书脊厚度与书籍高度的比例是否合理
        /// </summary>
        private void CheckSpineRatio(int pages, double spineThickness)
        {
            // 简单估算书籍高度（假设每页高度为0.2mm）
            double estimatedHeight = pages * 0.2;

            // 计算比例
            double ratio = spineThickness / estimatedHeight;

            if (ratio > 0.5)
            {
                MessageBox.Show($"警告：书脊厚度与书籍高度比例较高({ratio:F2})，请检查参数是否合理。",
                    "比例警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 转换单位
        /// </summary>
        private double ConvertUnit(double value)
        {
            return isMillimeter ? value : value / 25.4;
        }

        /// <summary>
        /// 获取当前单位符号
        /// </summary>
        private string GetUnitSymbol()
        {
            return isMillimeter ? "毫米" : "英寸";
        }

        /// <summary>
        /// 计算书脊厚度
        /// </summary>
        private double CalculateSpineThickness(int pages, double thicknessPerPage, string bindingType)
        {
            // 获取装订系数
            double bindingFactor = bindingFactorMap[bindingType];

            // 计算书脊厚度（页数/2 × 每页厚度 × 装订系数）
            // 除以2是因为每张纸有两页
            double spineThickness = (pages / 2.0) * thicknessPerPage * bindingFactor;

            return spineThickness;
        }

        /// <summary>
        /// 自定义纸张复选框状态改变事件
        /// </summary>
        private void checkCustomPaper_CheckedChanged(object sender, EventArgs e)
        {
            bool custom = checkCustomPaper.Checked;
            labelCustomThickness.Visible = custom;
            numericCustomThickness.Visible = custom;
            comboPaperType.Enabled = !custom;
        }

        /// <summary>
        /// 显示/隐藏高级选项按钮点击事件
        /// </summary>
        private void buttonAdvanced_Click(object sender, EventArgs e)
        {
            // 切换高级选项组的可见性
            groupBoxAdvanced.Visible = !groupBoxAdvanced.Visible;

            // 更新按钮文本
            buttonAdvanced.Text = groupBoxAdvanced.Visible ? "隐藏高级选项" : "显示高级选项";

            // 调整控件位置
            if (groupBoxAdvanced.Visible)
            {
                // 显示高级选项时的布局
                buttonCalculate.Top = 340;
                buttonAdvanced.Top = 340;
                buttonSaveConfig.Top = 340;
                groupBoxResults.Top = 380;  
            }
            else
            {
                // 隐藏高级选项时的布局（恢复原位）
                buttonCalculate.Top = 340;
                buttonAdvanced.Top = 340;
                buttonSaveConfig.Top = 340;
                groupBoxResults.Top = 170;  // 恢复到170位置
            }

            // 调整窗体高度
            this.Height = groupBoxAdvanced.Visible ? 650 : 480;

            // 强制刷新界面
            this.Refresh();
        }

        /// <summary>
        /// 计算按钮点击事件
        /// </summary>
        private void buttonCalculate_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取输入参数
                int pages = (int)numericPages.Value;
                string coverType = comboCoverType.SelectedItem.ToString();
                string bindingType = comboBindingType.SelectedItem.ToString();

                // 获取纸张厚度
                double thicknessPerPage;
                if (checkCustomPaper.Checked)
                {
                    thicknessPerPage = (double)numericCustomThickness.Value;
                }
                else
                {
                    string paperType = comboPaperType.SelectedItem.ToString();
                    thicknessPerPage = paperThicknessMap[paperType];
                }

                // 计算书脊厚度
                double spineThickness = CalculateSpineThickness(pages, thicknessPerPage, bindingType);

                // 获取封面厚度
                double coverThickness = coverThicknessMap[coverType];

                // 计算总厚度
                double totalThickness = spineThickness + coverThickness;

                // 转换单位
                if (!isMillimeter)
                {
                    spineThickness = ConvertUnit(spineThickness);
                    totalThickness = ConvertUnit(totalThickness);
                }

                // 显示结果
                string unit = GetUnitSymbol();
                labelSpineResult.Text = $"书脊厚度: {spineThickness:F2} {unit}";
                labelTotalResult.Text = $"总厚度(含封面): {totalThickness:F2} {unit}";

                // 检查比例是否合理
                CheckSpineRatio(pages, spineThickness);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"计算错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 保存设置按钮点击事件
        /// </summary>
        private void buttonSaveSettings_Click(object sender, EventArgs e)
        {
            try
            {
                // 更新单位设置
                isMillimeter = radioMillimeter.Checked;

                // 更新默认值
                int defaultPages = (int)numericDefPages.Value;
                string defaultPaper = comboDefPaper.SelectedItem.ToString();
                string defaultCover = comboDefCover.SelectedItem.ToString();

                // 应用默认值到计算器
                numericPages.Value = defaultPages;
                comboPaperType.SelectedItem = defaultPaper;
                comboCoverType.SelectedItem = defaultCover;

                MessageBox.Show("设置已保存并应用", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存设置时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void toolStripStatusLabel1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://space.bilibili.com/3493128132626725");//海棠云螭的B站
        }
    }
}